/**
 * 主布局组件
 * 
 * 功能描述：
 * - 应用的主要布局容器组件
 * - 管理顶部导航栏和底部导航栏的显示逻辑
 * - 根据路由自动切换底部导航的活跃状态
 * - 提供响应式的移动端布局结构
 * 
 * 使用场景：
 * - 作为应用的主要布局框架
 * - 统一管理导航栏的显示和隐藏
 * - 提供一致的用户界面结构
 * 
 * 作者：系统
 * 创建时间：2024
 */

import { useState, useEffect } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import Header from './Header';
import BottomNavigation from './BottomNavigation';

export default function Layout() {
  const location = useLocation();
  const navigate = useNavigate();
  
  // 根据当前路径确定活跃的标签
  const getActiveTab = () => {
    const path = location.pathname;
    if (path === '/') return 'medical';
    if (path === '/messages') return 'messages';
    if (path === '/orders') return 'orders';
    return 'medical';
  };

  const [activeTab, setActiveTab] = useState<'medical' | 'messages' | 'orders'>(getActiveTab());

  // 当路径改变时更新活跃标签
  useEffect(() => {
    const newActiveTab = getActiveTab();
    setActiveTab(newActiveTab);
  }, [location.pathname]);

  const handleTabChange = (tab: 'medical' | 'messages' | 'orders') => {
    setActiveTab(tab);
    switch (tab) {
      case 'medical':
        navigate('/', { replace: true });
        break;
      case 'messages':
        navigate('/messages', { replace: true });
        break;
      case 'orders':
        navigate('/orders', { replace: true });
        break;
    }
  };

  // 判断是否显示底部导航
  const shouldShowBottomNav = () => {
    const path = location.pathname;
    return !path.includes('/doctor/') && !path.includes('/consultation/') && !path.includes('/profile');
  };

  // 判断是否显示顶部栏 - 只在首页显示
  const shouldShowHeader = () => {
    return location.pathname === '/';
  };

  return (
    <div className="mobile-container flex flex-col h-screen bg-gray-50">
      {/* 只在首页显示蓝色顶部栏 */}
      {shouldShowHeader() && <Header />}
      <main className="flex-1 overflow-y-auto pb-20">
        <Outlet />
      </main>
      {shouldShowBottomNav() && (
        <div className="fixed bottom-0 left-1/2 transform -translate-x-1/2 w-full max-w-md z-50">
          <BottomNavigation 
            activeTab={activeTab}
            onTabChange={handleTabChange}
          />
        </div>
      )}
    </div>
  );
} 